<template>
  <el-drawer
    :visible.sync="showDrawer"
    :with-header="false"
    :close="handleClose"
    :before-close="handleClose"
    :size="showMobilePage ? '100%' : 640"
    class="audit-process"
  >
    <div class="header">
      <SectionTitle title="审批流程人员选择" font-size="16px" style="margin-left:24px">
        <div v-if="!isModify && showRefresh" class="center">
          <span class="text">当前审批流有更新，请</span>
          <div class="refresh" @click="refresh">
            <span>刷新</span>
            <el-image :src="refreshImg" class="img" />
          </div>
          <tip-icon content="自定义表单流程的部分配置不支持更新哦~" />
        </div>
        <div v-else-if="isModify && isModifyForm" class="text">流程节点修改中</div>
        <div v-else-if="isModify && showRefresh" class="text">审批流程有变更，可刷新获取最新流程</div>
        <div v-else class="text">当前审批流已是最新</div>
      </SectionTitle>
      <div v-if="isModify && !isModifyForm" class="center mr10">
        <div class="refresh" @click="refresh">
          <span>刷新可编辑</span>
          <el-image :src="refreshImg" class="img" />
        </div>
      </div>
    </div>
    <div v-loading="loading" class="audit-process-wrap scroll">
      <el-timeline v-if="flowStructure && processStructure.length > 1" class="not-icon-timeline">
        <template v-for="(struct, index) in processStructure">
          <el-timeline-item
            :key="index"
            color="#AEB6C7"
          >
            <div v-for="(role, roleIndex) in struct.examineRoles" :key="role.id" class="process-item-row">
              <div v-if="selectData.process[index]" :style="{'min-height': processItemMinHeight + 'px'}" class="process-item-box">
                <div class="process-dec-wrap">
                  <div class="process-dec">
                    <span class="process-name">{{ struct.nodeType ===3 ? struct.nodeName : role.roleName }}
                      <el-tooltip :open-delay="300" placement="top" effect="dark">
                        <div slot="content" style="max-width:300px">{{ struct.explanation }}</div>
                        <i v-if="struct.explanation && roleIndex === 0" class="el-icon-question ml2"/>
                      </el-tooltip>
                    </span>
                    <div v-if="struct.nodeType ===4 && struct.accountNames && struct.accountNames.length" class="auditor-num">
                      <div v-for="(name, index) in struct.accountNames" :key="index">账号：{{ name }}</div>
                      <div v-if="struct.cooperation" class="mt2">合作运营方：{{ struct.cooperation }}</div>
                    </div>
                    <span v-else-if="struct.nodeType ===3" class="auditor-num">共抄送{{ selectData.process[index].examineRoles[roleIndex].aduitors.length }}人</span>
                    <span v-else-if="role.roleType !== ROLE_TYPE.INITIATING_NODE && struct.nodeType !==3" class="auditor-num">{{ selectData.process[index].examineRoles[roleIndex].aduitors.length }}人审批</span>
                  </div>
                </div>
                <div class="auditor-select-box">
                  <div v-if="selectData.process[index].examineRoles[roleIndex].aduitors.length > (showMobilePage ? 1 : 2)" :style="{'height': avatorSize + 'px'}" :class="[ role.userRelation === 1 ? 'and' : 'or']" class="select-item">
                    <check-more-btn @click="addAudit(role, index, roleIndex, struct.nodeType === 3 ? '抄送人' : selectData.process[index].examineRoles[roleIndex].roleName || '审批人', struct.roleRelation)" />
                  </div>
                  <div v-for="(audit, i) in returnArr(selectData.process[index].examineRoles[roleIndex].aduitors, showMobilePage ? 2 : 3)" :key="audit.id" :style="{'height': avatorSize + 'px'}" :class="[ role.userRelation === 1 ? 'and' : 'or']" class="select-item">
                    <delete-avator :is-fly-user="role.roleType === ROLE_TYPE.FLYNOTICE" :disable="(disable && !hasRefresh) || role.roleType === ROLE_TYPE.INITIATING_NODE" :user="handleUser(audit)" @deleteFun="rolesDelete(index, roleIndex, i)"/>
                  </div>
                  <div v-if="(!disable || hasRefresh ) && ![ROLE_TYPE.INITIATING_NODE, ROLE_TYPE.FLYNOTICE].includes(role.roleType) " :style="{'height': avatorSize + 'px'}" :class="[ role.userRelation === 1 ? 'and' : 'or']" class="select-item">
                    <div v-if="selectData.process[index].examineRoles[roleIndex].isErrNode" class="err-tip">请选择审批人</div>
                    <add-btn :size="avatorSize" :relation="struct.roleRelation" :is-require="struct.isRequire" :show-relation="roleIndex < struct.examineRoles.length -1" @add="addAudit(role, index, roleIndex, struct.nodeType === 3 ? '添加抄送人' : '添加审批人', struct.roleRelation)"/>
                  </div>
                </div>
              </div>
            </div>
          </el-timeline-item>
        </template>
        <el-timeline-item
          color="#AEB6C7"
          class="last-line"
        >
          <div class="send-to">
            <div class="send-to-dec">
              <span class="title">抄送</span>
              <span class="send-num">共抄送{{ selectData.senders.length }}人</span>
            </div>
            <div class="sender-select-box">
              <div v-if="!disable || hasRefresh" :style="{'height': avatorSize + 'px'}" class="select-item or">
                <add-btn :size="avatorSize" @add="addSender(selectData.senders)"/>
              </div>
              <div v-for="(sender, sendIndex) in returnArr(selectData.senders, 3)" :key="sender.id" :style="{'height': avatorSize + 'px'}" class="select-item or">
                <delete-avator :disable="(sender.lock || disable) && !hasRefresh" :user="sender" @deleteFun="senderDelete(sendIndex)"/>
              </div>
              <div v-if="selectData.senders.length > 2" :style="{'height': avatorSize + 'px'}" class="select-item or">
                <check-more-btn @click="addSender(selectData.senders, '抄送人')" />
              </div>
            </div>
          </div>
        </el-timeline-item>
      </el-timeline>
      <div v-else class="none-process">
        <img :src="emptyImg" alt="">
        <div class="empty-text">没有符合条件的审批流程，请调整表单内容或联系管理员</div>
      </div>
      <auditor-dialog ref="auditorShowAllDialog" />
      <divers-auditor-dialog ref="auditorDialog" :max-num="Infinity" @userSelect="userSelect" @refresh="setShowRefresh(true)"/>
    </div>
    <fixed-pagination :style="{width:showMobilePage ? '100%' : '640px'}" style="margin:0; padding:0">
      <div class="center mobile-btn-group">
        <el-checkbox v-if="isShowReApplyBtn" v-model="isReApplyAfterCall" :class="{'mobile-re-apply': showMobilePage}" class="re-apply">发起后继续申请</el-checkbox>
        <el-button :disabled="submitLoading" type="primary" size="small" class="empty-btn-style mobile-btn-flex" @click="handleSubmit">{{ btnText }}</el-button>
        <el-button type="info" size="small" class="back-btn cancel-btn-style" @click="handleClose">取消</el-button>
      </div>
    </fixed-pagination>
    <modifySenders ref="modifySenders" :process="process" :default-aduitor-list="defaultAduitorList" @handleModify="handleModify"/>
  </el-drawer>
</template>
<script>
import AddBtn from './module/addBtn';
import CheckMoreBtn from './module/checkMoreBtn';
import DeleteAvator from '@/components/DeleteAvator';
import AuditorDialog from './module/auditorDialog';
import DiversAuditorDialog from './module/diversAuditorDialog';
import SectionTitle from '@/components/Title';
import modifySenders from '@/components/Common/auditProcess/module/modifySenders';
import emptyImg from '@/assets/process_empty.png';
import refreshImg from '@/assets/auditProcess/refresh.png';
import { showModal } from '@/utils/message';
import { ROLE_TYPE } from '@/utils/const/process';
import { mapState } from 'vuex';

export default {
  name: 'AuditProcess',
  components: { AddBtn, DeleteAvator, CheckMoreBtn, AuditorDialog, DiversAuditorDialog, SectionTitle, modifySenders },
  model: {
    prop: 'processData',
    event: 'change'
  },
  props: {
    flowStructure: {
      type: Object,
      default: () => {
        return {
          process: []
        };
      }
    },
    processData: {
      type: Object,
      default: () => {
        return null;
      }
    },
    avatorSize: {
      type: Number,
      default: 40
    },
    processItemMinHeight: {
      type: Number,
      default: 78
    },
    disable: { // 是否可编辑 false: 可编辑
      type: Boolean,
      default: false
    },
    defaultAduitorList: { // 申请人
      type: Array,
      default: () => {
        return [];
      }
    },
    defaultAuthUserList: { // 授权人
      type: Array,
      default: () => {
        return [];
      }
    },
    loading: {
      type: Boolean,
      default: false
    },
    btnText: {
      type: String,
      default: '发起审批'
    },
    isModify: {
      type: Boolean,
      default: false
    },
    isModifyForm: {// 节点修改
      type: Number,
      default: 0
    },
    currentProcessIndex: {// 当前节点索引
      type: Number,
      default: -1
    },
    oldAuditInfo: {// 详情接口流程数据，用于展示节点修改提示人员
      type: Object,
      default: () => {
        return {
          process: []
        };
      }
    },
    submitLoading: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      ROLE_TYPE,
      tempAduitor: null,
      emptyImg,
      refreshImg,
      hasRefresh: false,
      showDrawer: false,
      showRefresh: false, // 是否显示刷新按钮
      antiShakeTime: 0, // 防抖时间
      isReApplyAfterCall: false
    };
  },
  computed: {
    ...mapState({
      'device': state => state.app.device,
      'showMobilePage': state => state.app.showMobilePage
    }),
    // 当前节点之前的节点
    process() {
      if (this.currentProcessIndex === -1 || !this.oldAuditInfo) { return []; }
      const process = this.oldAuditInfo.process.slice(0, this.currentProcessIndex + 1);
      return process;
    },
    selectData: {
      get() {
        return this.processData;
      },
      set(val) {
        this.$emit('change', val);
      }
    },
    // 通过过滤后的 审批结构 v2.8.6 是否需要去除加签节点逻辑
    processStructure() {
      if (!this.flowStructure) return [];
      return this.flowStructure.process;
    },
    isShowReApplyBtn() {
      return this.$route.name === 'supplierCreate' || this.$route.name === 'supplierEdit' && !this.isModify;
    }
  },
  methods: {
    handleUser(user) {
      user.hasOwnProperty('isRead') && delete user.isRead;
      user.hasOwnProperty('userStatus') && delete user.userStatus;
      return user;
    },
    openDrawer() {
      this.showDrawer = true;
    },
    setShowRefresh(isShow) {
      this.showRefresh = isShow;
    },
    handleClose() {
      this.showDrawer = false;
      this.hasRefresh = false;
    },
    handleSubmit() { // 发起审批
      if (!this.isValid()) {
        this.$message({
          type: 'warning',
          message: '请检查流程审批人填写是否完整'
        });
        return;
      }
      if (this.isModifyForm) {
        this.$refs.modifySenders.openDialog();
      } else {
        this.$emit('submit');
      }
    },
    handleModify(senders = []) {
      this.$emit('submit', senders);
    },
    refresh() { // 刷新流程
      const timestamp = Date.parse(new Date());
      if (timestamp - this.antiShakeTime < 500) {
        return;
      }
      this.antiShakeTime = timestamp;
      showModal('请确认是否刷新流程', '', {
        iconClass: 'del-icon'
      }).then(() => {
        this.setShowRefresh(false);
        this.hasRefresh = true;
        this.$emit('getProcess');
      }).catch(() => {
        return false;
      });
    },
    // 返回数组的前两个
    returnArr(arr, length) {
      if (arr.length < length) {
        return arr;
      }
      const temp = [];
      for (let i = 0; i < length - 1; i++) {
        if (arr[i]) temp.push(arr[i]);
      }
      return temp;
    },
    rolesDelete(index, roleIndex, i) {
      this.selectData.process[index].examineRoles[roleIndex].aduitors.splice(i, 1);
    },
    senderDelete(index) {
      this.selectData.senders.splice(index, 1);
      this.$forceUpdate();
    },
    addAudit(examineRole, index, roleIndex, title = '添加审批人', roleRelation) {
      const aduitors = this.selectData.process[index].examineRoles[roleIndex].aduitors;
      const param = {
        index,
        roleIndex,
        aduitors,
        allowSelectOther: examineRole.allowSelectOther || examineRole.isTopLeader,
        examineRoleId: examineRole.id,
        roleType: examineRole.roleType,
        departmentList: examineRole.departmentList,
        defaultAduitorList: examineRole.roleType === ROLE_TYPE.PROPOSER ? this.defaultAduitorList : this.defaultAuthUserList,
        designateUsers: examineRole.diyUserList || [],
        roleRelation
      };
      this.$refs.auditorDialog.dialogVisible = true;
      this.$refs.auditorDialog.initData(param, title);
    },
    addSender(param, title = '添加抄送人') {
      this.$refs.auditorDialog.dialogVisible = true;
      this.$refs.auditorDialog.initSenderData(param, title);
      const lockIds = [];
      param && param.map(item => {
        if (item.lock) lockIds.push(item.id);
      });
      localStorage.setItem('sendersLockIds', JSON.stringify(lockIds));
    },
    userSelect(param) {
      if (param.tempData) {
        const index = param.tempData.index;
        const roleIndex = param.tempData.roleIndex;
        this.selectData.process[index].examineRoles[roleIndex].aduitors = param.selectUser;
        if (param.selectUser && param.selectUser.length) {
          if (param.tempData.roleRelation) { // 且
            this.selectData.process[index].examineRoles[roleIndex].isErrNode = false;
          } else {
            this.selectData.process[index].examineRoles.map(el => {
              el.isErrNode = false;
            });
          }
        }
      } else {
        this.selectData.senders = param.selectUser;
        this.$forceUpdate();
      }
    },
    showAll(presons) {
      this.$refs.auditorShowAllDialog.dialogVisible = true;
      this.$refs.auditorShowAllDialog.initShowAll(presons);
    },
    isValid() {
      let valid = true;
      const process = this.flowStructure.process;
      const selectProcess = this.selectData.process;
      for (let i = 0; i < process.length; i++) {
        if (process[i].isRequire === 1) {
          if (process[i].roleRelation) {
            // 关系且
            for (let e = 0; e < process[i].examineRoles.length; e++) {
              if (!selectProcess[i].examineRoles[e].aduitors || (selectProcess[i].examineRoles[e].aduitors && selectProcess[i].examineRoles[e].aduitors.length === 0)) {
                selectProcess[i].examineRoles[e].isErrNode = true;
                valid = false;
              } else {
                selectProcess[i].examineRoles[e].isErrNode = false;
              }
            }
          } else {
            // 关系或
            let hasSelect = false;
            for (let e = 0; e <= process[i].examineRoles.length - 1; e++) {
              if (selectProcess[i].examineRoles[e].aduitors && selectProcess[i].examineRoles[e].aduitors.length > 0) {
                hasSelect = true;
              }
            }
            if (!hasSelect) {
              selectProcess[i].examineRoles.map(el => {
                el.isErrNode = true;
                valid = false;
              });
            } else {
              selectProcess[i].examineRoles.map(el => {
                el.isErrNode = false;
              });
            }
          }
        }
      }
      this.$forceUpdate();
      return valid;
    }
  }
};
</script>
<style lang="scss" scoped>
.audit-process{
  &::v-deep {
  .el-drawer__body {
    overflow: unset;
   }
  }
}
.err-tip {
  font-size: 14px;
  color: red;
  transform: translateY(10px);
  margin-right: 12px;
}
.header{
  display: flex;
  height: 48px;
  align-items: center;
  box-shadow: 0px 3px 7px -7px #5E5E5E;
  .center{
    display: flex;
    align-items: center;
    flex-wrap: nowrap;
  }
  .text{
    color: #999999;
    margin-left: 8px;
    font-size: 14px !important;

  }
  .refresh{
    display: flex;
    align-items: center;
    color: #406EFF;
    font-size: 14px !important;
    cursor: pointer;
  }
  .img{
    width: 14px;
    height: 14px;
    flex-shrink: 0;
    margin-left: 4px;
  }
}
.scroll {
  max-height: calc(100vh - 35px);
  overflow-y: auto !important;
}
.audit-process-wrap {
  padding:13px 72px 56px 24px;
  .audit-operator {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 10px;
  }
  & ::v-deep {
    .el-timeline {
      padding-top: 10px;
      padding-left: 0;
    }
    .el-timeline-item__wrapper {
      top: -10px;
      padding-left: 26px;
    }
    .el-timeline-item__node--normal{
      left: 0;
      width: 10px;
      height: 10px;
    }
    .el-timeline-item:last-child .el-timeline-item__tail{
      display: none !important;
    }
  }
  .process-item-row:last-child {
    border-bottom: 1px solid #FAFAFC;
  }
  .process-item-box {
    display: flex;
    // padding-bottom: 9px;
    .process-dec-wrap {
      display: flex;
      flex: 1;
      .require-flag {
        margin-right: 10px;
        color: #E54C4C;
      }
      .process-dec {
        display: flex;
        flex: 1;
        flex-direction: column;
        width: 0;
        .process-name {
          display: block;
          overflow: hidden;
          text-overflow:ellipsis;
          white-space: nowrap;
          font-size: 16px;
          color: #333333;
        }
        .auditor-num {
          margin-top: 2px;
          font-size: 12px;
          color: #999999;
        }
      }
    }
  }
  .auditor-select-box,
  .sender-select-box {
    display: flex;
    .select-item {
      display: flex;
    }
    .select-item:first-child {
      &::before {
        content: " ";
        display: block;
        margin: 0;
      }
    }
    .or::before {
      content: "/";
      display: flex;
      align-items: center;
      margin: 0 10px;
      font-size: 15px;
      color: #999;
    }
    .and::before {
      content: "+";
      display: flex;
      align-items: center;
      margin: 0 10px;
      font-size: 15px;
      color: #999;
    }
  }
  .send-to {
    display: flex;
    .send-to-dec {
      display: flex;
      flex-direction: column;
      margin-right: 17px;
      .title {
        margin-bottom: 6px;
        font-size: 16px;
        color: #333333;
      }
      .send-num {
        font-size: 12px;
        color: #999999;
      }
    }
  }
}
.re-apply {
  position: absolute;
  left: 16px;
  line-height: 32px;
}
.mobile-re-apply {
  position: unset;
  left: unset;
  margin-right: 8px;
}
.none-process {
  text-align: center;
  position: relative;
  margin-top: 180px;
  margin-left: 48px;
  img {
    width: 120px;
    height: 118px;
  }
  .empty-text {
    color: #999;
    font-size: 14px;
  }
}
</style>
